package  
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	/**
	 * ...
	 * @author cjay
	 */
	public class Lerp
	{
		
		private static var _instance:Lerp;
		private static var timer:Timer;
		
		private static var items:Array;
		public static var frameRate:int=25;
		
		public function Lerp() 
		{
			timer = new Timer(1000/25);
			timer.addEventListener(TimerEvent.TIMER, timeHandler);
			items = new Array();
		}
		
		public static function getInstance():Lerp
		{
			if (!_instance) 
			{
				_instance = new Lerp();
			}
			
			return _instance;
		}
		
		public function to(item:Object,len:Number, params:Object):void
		{
			var obj:Object = new Object;
			obj.target = item;
			obj.time = len;
			obj.params = params;
			obj.step = 0;

			items.push(obj);
			
			if (!timer.running) timer.start();	
			
		}
		private function lerpFor(obj:Object):void
		{
			var target:Object = obj.target;
			var tTime:int = obj.time * frameRate;
			obj.step++;
			var percent:Number = obj.step / tTime;
			
			
			for (var name:String in obj.params)
			{
				if (name == "handler") continue;
				target[name] = target[name] + (percent) * (obj.params[name] - target[name]);
			}
			if (percent >= 1.0)
			{
				if ("handler" in obj.params) obj.params.handler();
				items.splice(items.indexOf(obj), 1);
			}
		}
		
		private function timeHandler(event:Event):void
		{	
			if (items.length < 1) 
			{
				timer.stop();
				return;
			}
			
			for each (var item:Object in items) {
				lerpFor(item);
			}
		}
		
		
		
		
		
	}

}